Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

For Loop

For loop in java

What is For Loop?

A for loop is a control flow statement that allows you to execute a block of code repeatedly until a certain condition is met. The for loop has three parts: Initialization: This is a statement that is executed once before the loop starts. Condition: This is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, then the block of code is executed. Increment: This is a statement that is executed after each iteration of the loop. It is used to update the value of the loop variable. Here is the syntax for the for loop:
For loop syntax
for (initialization; condition; increment) { // block of code }
The initialization statement is executed once before the loop starts. The condition statement is evaluated before each iteration of the loop. If the condition is true, then the block of code is executed. The increment statement is executed after each iteration of the loop. Here is an example of a for loop:
for loop example public class Main{ public static void main(String[] args){ for (int i = 0; i < 10; i++) { System.out.println(i); } } }

Output

0 1 2 3 4 5 6 7 8 9
In this example, the for loop will print the numbers from 0 to 9. The initialization statement in this example is int i = 0;. This statement declares a variable called i and initializes it to 0. The condition statement in this example is i < 10;. This statement checks if the value of i is less than 10. If it is, then the block of code is executed. The increment statement in this example is i++;. This statement increments the value of i by 1. The block of code in this example is the statement System.out.println(i);. This statement prints the value of i to the console. The for loop is a versatile control flow statement that can be used to implement a variety of looping patterns. It is a good choice when you know how many times you want to loop.

Here are some additional things to keep in mind about for loops:

1. The initialization statement can be any statement that does not have a side effect. 2. The condition statement can be any boolean expression. 3. The increment statement can be any statement that does not have a side effect. 4. The block of code can be any block of statements. 5. The for loop can be nested.

  📌TAGS

★loop ★looping statement ★control statement ★control in java ★loops in java ★for ★while ★do while ★for each

Tutorials